// 测试;


// const { default: axios } = require("axios");

// function throttle(callback,wait){ 
//     let start = 0; return function(){
//      let now = Date.now(); if (now - wait > start){ 
//          callback.call(this,event); start = now; 
//         } } }
//         document.getElementById("right_wrap").addEventListener('scroll',throttle(function(e){
//         console.log(document.getElementById("right_wrap").scrollTop); 
//     },500))
// function fun_a(){
//     if (document.querySelector('.admin').getAttribute("username")!='wlgzs') {
//         window.location.reload()
//     }
// }
// fun_a();
const onfocusFun = e => {
    // alert(document.getElementById("right_wrap").scrollTop)
    e=e || window.event;
   var target=e.target || e.srcElement;
   if(target.getAttribute("id")!="search_input"){
    target.style.backgroundColor = "#68ADCA";
    target.style.color = "#fff";
    flagPassword=target.innerHTML
   }
   if(target.getAttribute("flag")==1){
    flagName=target.innerHTML;
   }else if(target.getAttribute("flag")==2){
    flagUsername=target.innerHTML;
   }else if(target.getAttribute("flag")==3){
       flagPassword=target.innerHTML;
   }
   
//    console.log(target);
 }
 var flagPassword,flagName,flagUsername;
const onblurFun = e => {
    e=e || window.event;
   var target=e.target || e.srcElement;
   if(target.getAttribute("id")!="search_input"){
    target.style.color = "#666";
    target.style.background = "transparent";
    // console.log(target.innerHTML);
    if(target.getAttribute("flag")==1){
        // flagName=target.innerHTML;
        if(target.innerHTML!=flagName){
            axios({
                url:"/admin/users/updateUserPassword",
                method:"GET",
                params:{
                    id:target.getAttribute("id"),
                    name:target.innerHTML,
                    username:target.getAttribute("username"),
                    classId:target.getAttribute("classId"),
                    studentId:target.getAttribute("studentId"),
                    sex:target.getAttribute("sex"),
                    password:target.getAttribute("password")
                    }
                })
                .then(data=>{
                    // console.log(data);
                    // successSpan.innerHTML="密码用户姓名成功"
                    // shouSuccessFun()
                    // layer.msg('用户姓名修改成功');
                    layui.use("layer",function(){
                        layer.msg('用户姓名修改成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                })
                .catch(err=>{
                    console.log(err);
                })
        }
        
    }else if(target.getAttribute("flag")==2){
    // flagUsername=target.innerHTML;
        if(target.innerHTML!=flagUsername){
            axios({
                url:"/admin/users/updateUserPassword",
                method:"GET",
                params:{
                    id:target.getAttribute("id"),
                    name:target.getAttribute("name"),
                    username:target.innerHTML,
                    classId:target.getAttribute("classId"),
                    studentId:target.getAttribute("studentId"),
                    sex:target.getAttribute("sex"),
                    password:target.getAttribute("password")
                    }
                })
                .then(data=>{
                    // console.log(data);
                    // successSpan.innerHTML="修改用户账号成功"
                    // shouSuccessFun()
                    // layer.msg('修改用户账号成功');
                    layui.use("layer",function(){
                        layer.msg('用户账号修改成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                })
                .catch(err=>{
                    console.log(err);
                })
        }
    }else if(target.getAttribute("flag")==3){
        // flagPassword=target.innerHTML;
        if(target.innerHTML!=flagPassword){
            axios({
                url:"/admin/users/updateUserPassword",
                method:"GET",
                params:{
                    id:target.getAttribute("id"),
                    name:target.getAttribute("name"),
                    username:target.getAttribute("username"),
                    classId:target.getAttribute("classId"),
                    studentId:target.getAttribute("studentId"),
                    sex:target.getAttribute("sex"),
                    password:target.innerHTML
                    }
                })
                .then(data=>{
                    // console.log(data);
                    // successSpan.innerHTML="密码修改成功"
                    // shouSuccessFun()
                    // layer.msg('密码修改成功');
                    layui.use("layer",function(){
                        layer.msg('用户密码修改成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                })
                .catch(err=>{
                    console.log(err);
                })
        }
    }
    
   
   
   target.style.borderColor="#black";
   }
   
 }


//  获取后台数据，渲染页面
var tybody = qu("#tybody");
var page=1,
   pageSize=5,
   datas,
   counts; 
   initFun()
function initFun(){
    var getcounts = ()=> {
        return new Promise((resolve, reject) => {
            axios({
                url:"/admin/users/findAllUsers",
                method:"GET",
                params: {
                    pageNow:page,
                    pageSize :pageSize
                    }
                }).then(data=>{
                    // console.log(data);
                    // datas=data.data.user.list
                    resolve(data)
                });
        })
        
    }
    getcounts().then(data=>{
        // console.log(data);
        counts=data.data.user.pageTotalCount
        pageSize=data.data.user.pageSize
        datas=data.data.user
        // carryOutFun()
        layui.use(['laypage', 'layer'], function(){
            let arr_length =new Array();
            if(counts<=5){
                arr_length=[counts];
            }else if(counts<=10&&counts>5){
                arr_length=[5,counts];
            }else if(counts>10&&counts<=20){
                arr_length=[5,10,counts];
            }else if(counts>20){
                arr_length=[5,10,20,counts];
            }
            console.log(arr_length);
           var laypage = layui.laypage
           ,layer = layui.layer;
           laypage.render({
               elem: 'demo7'
               ,count: counts
               ,curr:page
               ,limit:pageSize
               ,limits: arr_length
               ,layout: ['count', 'prev', 'page', 'next', 'limit']
               ,jump: function(obj){
                //  console.log(obj);
                 page=obj.curr;
                 pageSize=obj.limit;
                 getData(page,pageSize);
                 dels=[]
                 checkAll.checked = false;
                //  console.log(dels);
                //  changePage();
               }
           });
        });
        
    });
    
}

const getData=(a,b)=>{
   // 传参
   if(pageSize>=counts) pageSize=counts;
   // 获得数据
   axios({  
    url:"/admin/users/findAllUsers",
    method:"GET",
    params: {
        pageNow:a,
        pageSize :b
        }
    })
    .then(function(result){
        datas=result.data.user
        console.log(result);
        tybody.innerHTML=''
        let i;
            // for(i=(a-1)*datas.pageSize; i<((a-1)*datas.pageSize+datas.pageSize); i++){
                for(i=0; i<datas.list.length; i++){
                // <td>${datas.list[i].name}</td>
                // <td>${datas.list[i].username}</td>
                let _name=htmlEscape(datas.list[i].name) 
                let _username=htmlEscape(datas.list[i].username) 
                let _password=htmlEscape(datas.list[i].password) 
                tybody.innerHTML +=`
                <tr>
                    <td><input type="checkbox" class="checkbox" name="${datas.list[i].id}"  onclick="checkboxFun()" target="${i}"  ></td>
                    <td contentEditable="true" flag="1" id="${datas.list[i].id}" password="${datas.list[i].password}" username="${datas.list[i].username}" studentId="${datas.list[i].studentId}" sex="${datas.list[i].sex}" clsssId="${datas.list[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_name}</td>
                    <td contentEditable="true" flag="2" id="${datas.list[i].id}" name="${datas.list[i].name}" password="${datas.list[i].password}" studentId="${datas.list[i].studentId}" sex="${datas.list[i].sex}" clsssId="${datas.list[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_username}</td>
                    <td contentEditable="true" flag="3" id="${datas.list[i].id}" name="${datas.list[i].name}" username="${datas.list[i].username}" studentId="${datas.list[i].studentId}" sex="${datas.list[i].sex}" clsssId="${datas.list[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_password}</td>
                    <td>
                        <button class="layui-btn layui-btn-sm layui-btn-sm" onclick="initPasswordFun()" flag="1" name="${datas.list[i].password}" target="${datas.list[i].id}" >
                            初始化密码
                        </button>
                        <button class="layui-btn layui-btn-danger layui-btn-sm" onclick="delUserFun()" flag="2" target="${datas.list[i].id}">
                            删除
                        </button>
                        
                    </td>
                </tr>
                `
            }
    })
    .catch(err=>{
        console.log(err);
    })
}

// 开启弹窗; 
function openChangeWindowFun(){
   changeWindow.style.display="block";
   cover_div.style.display="block";
}
// 关闭弹窗
function closeChangeWindowFun(){
   changeWindow.style.display="none";
   cover_div.style.display="none";
}
// 提交
function changeOkFun(){
   closeChangeWindowFun();
}

// 选择状态
var change_li = cl("change_li");
function chooseStatusFun(e){
   e=e || window.event;
   var target=e.target || e.srcElement;
   for(let key of change_li){
       key.style.backgroundColor="#D8F3EE";
       key.style.color="rgb(115, 111, 111)";
   }
   target.style.backgroundColor = "#2BA5FE"
   target.style.color = "#fff"
}

function goAddFun(){
   window.location.href="../admin/users/addUsers"
}
// 初始化单个用户密码
function initPasswordFun(e){
    e=e || window.event;
   var target=e.target || e.srcElement;
   if(target.getAttribute('name')=="123456"){
    // successSpan.innerHTML="该用户密码已是初始化状态😅"
    // shouSuccessFun()
    layui.use("layer",function(){
        layer.msg('密码已是初始化状态', {
            icon: 6,
            time: 2000
        })
    })
   }else{
    axios({
        url:"/admin/users/updatePassword",
        method:"GET",
        params: {
            _id:target.getAttribute("target"),
            }
        }).then(data=>{
            
            // console.log(data.data);
            if (data.data.err==0) {
                getData(page,pageSize);
                // successSpan.innerHTML="初始化密码成功"
                // shouSuccessFun()
                    // layer.msg('初始化密码成功');
                    layui.use("layer",function(){
                        layer.msg('初始化密码成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                    // alert("初始化成功")
                // 清除初始化之前的选中状态
                dels.splice(dels.indexOf(target.getAttribute("target")),1)
            }
        });
   }
  
// console.log(target.getAttribute("target"));
}
// 批量初始化用户密码
function initAllPasswordFun(){
    if (dels.length==0) {
        // alert("请选中您要初始化密码的用户")
        layui.use("layer",function(){
            layer.msg('请选择您要初始化密码的用户！', {
                icon: 7,
                time: 2000
            })
        })
    }else{
        axios({
            url:"/admin/users/updateAllPassword",
            method:"GET",
            params: {
                _id:dels
            }
            }).then(data=>{
                // console.log(data);
                if (data.data.err==0) {
                    getData(page,pageSize);
                    // successSpan.innerHTML="初始化成功"
                    // shouSuccessFun()
                    // layer.msg('初始化成功');
                    layui.use("layer",function(){
                        layer.msg('初始化密码成功', {
                            icon: 1,
                            time: 2000
                        })
                    })

                    // alert("初始化成功")
                }
            });
    }
}
var flagDel = 0;
var delid;
// 删除单个用户
function delUserFun(e){
    e=e || window.event;
   var target=e.target || e.srcElement;
   delid=target.getAttribute("target");
   console.log(delid);
   cover_div.style.display="block"
   windowDiv.style.display="block"
   flagDel = 1;
}
// 批量删除
function delUsersFun(){
    if(dels.length==0){
        // alert("请选中您要删除的用户")
        layui.use("layer",function(){
            layer.msg('请选中您要删除的用户', {
                icon: 7,
                time: 2000
            })
        })
    }else{
        cover_div.style.display="block"
        windowDiv.style.display="block"
        flagDel = 2;
    }
}
// 查找用户
function seekUsersFun(){
    let nav_bottom = qu(".nav_bottom")
    // console.log(search_input.value==0);
    if (search_input.value==0 || search_input.value=="undefined"){
        // alert("请输入您要查找的用户姓名")
        layui.use("layer",function(){
            layer.msg('请输入您要查找的用户姓名', {
                icon: 7,
                time: 2000
            })
        })
        // location.reload();
    }else{
        console.log(search_input.value);
        axios({
            url:"/admin/users/seekUserByName",
            method:"GET",
            params: {
                name:search_input.value,
                }
            }).then(data=>{
                console.log(data);
                if(data.data.data.length>0){
                    nav_bottom.style.display="none"
                    tybody.innerHTML=''
                    let i;
                    for(i=0; i<data.data.data.length; i++){
                        let _name=htmlEscape(data.data.data[i].name) 
                        let _username=htmlEscape(data.data.data[i].username) 
                        let _password=htmlEscape(data.data.data[i].password) 
                        tybody.innerHTML +=`
                        <tr>
                            <td><input type="checkbox" class="checkbox" name="${data.data.data[i].id}"  onclick="checkboxFun()" target="${i}"  ></td>
                            <td contentEditable="true" flag="1" id="${data.data.data[i].id}" password="${data.data.data[i].password}" username="${data.data.data[i].username}" studentId="${data.data.data[i].studentId}" sex="${data.data.data[i].sex}" clsssId="${data.data.data[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_name}</td>
                            <td contentEditable="true" flag="2" id="${data.data.data[i].id}" name="${data.data.data[i].name}" password="${data.data.data[i].password}" studentId="${data.data.data[i].studentId}" sex="${data.data.data[i].sex}" clsssId="${data.data.data[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_username}</td>
                            <td contentEditable="true" flag="3" id="${data.data.data[i].id}" name="${data.data.data[i].name}" username="${data.data.data[i].username}" studentId="${data.data.data[i].studentId}" sex="${data.data.data[i].sex}" clsssId="${data.data.data[i].classId}" onfocus="onfocusFun()" onblur="onblurFun()">${_password}</td>
                            <td>
                                <button class="layui-btn layui-btn-sm layui-btn-sm" onclick="initPasswordFun()" name="${data.data.data[i].password}" flag="1" target="${data.data.data[i].id}" >
                                    初始化密码
                                </button>
                                <button class="layui-btn layui-btn-danger layui-btn-sm" onclick="delUserFun()" flag="2" target="${data.data.data[i].id}">
                                    删除
                                </button>
                                
                            </td>
                        </tr>
                        `
                       
                    }
                }else{
                    // alert("抱歉未找到")
                    layui.use("layer",function(){
                        layer.msg('抱歉未找到', {
                            icon: 2,
                            time: 2000
                        })
                    })
                }
            });
    }
}
function cancleDelFun(){
    cover_div.style.display="none"
    windowDiv.style.display="none"
    flagDel=0;
}
function submitDelFun(){
    console.log(flagDel==1);
    if(flagDel==1){
        axios({
            url:"/admin/users/deleteUser",
            method:"GET",
            params: {
                _id:delid,
                }
            }).then(data=>{
                // console.log(data.data);
                if (data.data.err==0) {
                    // getData(page,pageSize);
                    // location.reload();
                    cover_div.style.display="none"
                    windowDiv.style.display="none"
                    flagDel=0;
                    initFun()
                    // alert("删除成功")
                    layui.use("layer",function(){
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                }
            });
    }else{
        axios({
            url:"/admin/users/deleteAllUser",
            method:"GET",
            params: {
                _id:dels,
                }
            }).then(data=>{
                console.log(data.data);
                // console.log(data.data);
                if (data.data.err==0) {
                    // getData(page,pageSize);
                    // location.reload();
                    cover_div.style.display="none"
                    windowDiv.style.display="none"
                    flagDel=0;
                    initFun()
                    // alert("删除成功")
                    layui.use("layer",function(){
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 2000
                        })
                    })
                }
            });
    }
}
// 修改提示
function shouSuccessFun() {
    let i=0;
    successShow.style.display="block"
    // clearInterval(timer);
    let timer=setInterval(function(){
        if(i<1){
            i++
        }else{
            successShow.style.display="none"
            clearInterval(timer);
        }
    },500)
}